<template>
  <page-form-row :gutter="pageFormRowGutter">
    <page-form-item field="memberType" label="客户类型" :size="pageFormItemSize">
      <a-select
        placeholder="请选择"
        v-model="form.memberType"
        :disabled="['editOrder', 'editLesseeMemberModal'].includes(mode)"
        @change="changeMemberTypeFn"
      >
        <a-option v-for="item in dict.memberTypeEnum" :key="item.value" :label="item.label" :value="item.value" />
      </a-select>
    </page-form-item>
    <!-- 企业用户 -->
    <template v-if="form.memberType == 1">
      <page-form-item field="clientId" label="客户公司名称" :size="pageFormItemSize">
        <remote-select v-model="form.clientId" type="member_clientInfo" @change="changeClientFn" />
      </page-form-item>
      <page-form-item field="memberName" label="承租人" :size="pageFormItemSize" labelTooltipContent="请在会员管理中添加企业承租人">
        <template #label-extra>
          <tag :type="memberInfo.memberLabel == 2 ? 'success' : 'danger'" v-if="memberInfo.memberLabel == 2 || memberInfo.memberLabel == 3">
            {{ memberInfo.memberLabelName }}
          </tag>
        </template>
        <remote-select
          v-model="form.memberId"
          :params="{ clientId: form.clientId }"
          :mustParentShow="!form.clientId"
          mustParentTip="请先选择客户公司"
          type="member_list"
          @change="changeClientMemberFn"
        />
        <!-- <a-button type="primary" v-if="showUploadDriverBtn" @click="uploadDriverLicenseFn">未上传驾驶证</a-button> -->
      </page-form-item>
    </template>
    <!-- 个人用户 -->
    <template v-if="form.memberType == 2">
      <page-form-item field="memberPhone" label="联系电话" :size="pageFormItemSize">
        <template v-if="form.id" #label-extra>
          <a-link @click="onChangeMemberInfo">
            <template #icon>
              <icon-edit />
            </template>
            修改已选承租人信息
          </a-link>
        </template>
        <i-input
          v-if="memberPhoneList.length === 0 || memberPhoneList.length === 1"
          v-model="form.memberPhone"
          :max-length="11"
          @input="(value, ev) => memberPhoneInputFn(value, ev, form)"
          :disabled="memberPhoneList.length === 1"
          @clear="(ev) => memberPhoneInputFn(null, ev, form)"
        />
        <a-select
          v-else
          placeholder="请选择"
          v-model="form.memberPhone"
          allow-clear
          @change="(value) => memberPhoneChange(value, form)"
          @clear="() => memberPhoneInputFn(null, null, modalForm)"
        >
          <a-option v-for="item in memberPhoneList" :key="item.id" :label="item.phone" :value="item.phone" />
        </a-select>
      </page-form-item>
      <page-form-item field="memberName" label="承租人" :size="pageFormItemSize">
        <template #label-extra>
          <!-- memberStatus --(0:正常,1:已拉黑)memberLabel -- 1-普通会员，2-优质会员，3-风险会员 -->
          <tag
            v-if="props.type !== 'editMember'"
            :type="
              memberInfo?.memberStatus == 1 || memberInfo?.memberLabel == 3
                ? 'danger'
                : memberInfo?.memberLabel == 2
                ? 'success'
                : 'primary'
            "
          >
            {{ memberInfo?.memberStatus == 1 ? '已拉黑' : memberInfo?.memberLabelName }}
          </tag>
          <tag
            :type="memberInfo?.memberLabel == 2 ? 'success' : 'danger'"
            v-else-if="memberInfo?.memberLabel == 2 || memberInfo?.memberLabel == 3"
          >
            {{ memberInfo?.memberLabelName }}
          </tag>
        </template>
        <i-input
          :max-length="50"
          v-model="form.memberName"
          :disabled="memberPhoneResult"
          @input="(value, ev) => memberNameInputFn(form)"
          @clear="(ev) => memberNameInputFn(form)"
        />
        <!-- <a-button type="primary" v-if="showUploadDriverBtn" @click="uploadDriverLicenseFn">未上传驾驶证</a-button> -->
      </page-form-item>
    </template>
    <page-form-item label="证件类型" :size="pageFormItemSize" v-if="!isListEditMember">
      <a-select placeholder="请选择" v-model="form.cardType">
        <a-option v-for="item in dict.cardTypeEnum" :key="item.value" :label="item.label" :value="item.value" />
      </a-select>
    </page-form-item>
    <page-form-item field="cardNumber" label="证件号" :size="pageFormItemSize" v-if="!isListEditMember">
      <i-input :disabled="!form.memberName || !form.memberPhone" v-model="form.cardNumber" :max-length="18" placeholder="请输入" />
    </page-form-item>
    <page-form-item>
      <div class="card-btns" :class="{ 'edit-width': props.mode !== 'editLesseeMemberModal' }">
        <a-button v-if="showUploadIdCardBtn" class="id-btn" type="primary" @click="uploadIdCardFn">未上传身份证明</a-button>
        <a-button v-if="showUploadDriverBtn" type="primary" @click="uploadDriverLicenseFn">未上传驾驶证</a-button>
      </div>
    </page-form-item>
    <page-form-item field="cardAddress" label="证件住址" size="2/3" v-if="!isListEditMember">
      <i-input :disabled="!form.memberName || !form.memberPhone" v-model="form.cardAddress" :max-length="100" placeholder="请输入" />
    </page-form-item>
  </page-form-row>
  <!-- 紧急联系人、手机号 -->
  <page-form-row :gutter="pageFormRowGutter">
    <page-form-item label="紧急联系人" class="mb-0" :size="pageFormItemSize" v-if="!isListEditMember">
      <i-input v-model="form.emergencyContactName" :max-length="30" placeholder="请输入" />
    </page-form-item>
    <page-form-item field="emergencyContactPhone" label="紧急联系人手机号" class="mb-0" :size="pageFormItemSize" v-if="!isListEditMember">
      <a-input v-model="form.emergencyContactPhone" placeholder="请输入" :max-length="11" allow-clear @input="onInput" />
    </page-form-item>
  </page-form-row>
  <!-- 上传驾驶证照片 -->
  <upload-driver-license-modal ref="uploadDriverLicenseModalRef" :autoUpload="false" @ok="uploadSuccessFn" />

  <!-- 上传身份证明照片 -->
  <upload-id-card-modal ref="uploadIdCardModalRef" :autoUpload="false" @ok="uploadIdCardSuccessFn" />

  <a-modal v-model:visible="visible" width="45vw" title="修改已选承租人信息" :mask-closable="false" unmount-on-close>
    <page-form :model="modalForm" ref="modalFormRef" :rules="modalRules" auto-label-width>
      <page-form-row gutter="24">
        <page-form-item field="memberName" label="承租人" :size="'1/2'">
          <i-input :max-length="50" v-model="modalForm.memberName" />
        </page-form-item>
        <page-form-item field="memberPhone" label="联系电话" :size="'1/2'">
          <i-input v-model="modalForm.memberPhone" :max-length="11" />
        </page-form-item>
      </page-form-row>
    </page-form>
    <template #footer>
      <a-space>
        <a-button @click="onCancel">关闭</a-button>
        <a-button type="primary" @click="onConfirm" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>

  <a-modal v-model:visible="againConfirmVisible" width="45vw" title="确认修改承租人信息吗？" :mask-closable="false" unmount-on-close>
    <template #footer>
      <a-space>
        <a-button @click="onAgainCancel">关闭</a-button>
        <a-button type="primary" @click="onAgainConfirm">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { ref, inject, computed } from 'vue'
  import { useDebounceFn } from '@vueuse/core'
  import { findByPhone, getMemberInfo, checkMemberPhone } from '@/api/order/czsOrder'
  import uploadDriverLicenseModal from '../../components/upload-driver-license-modal.vue'
  import uploadIdCardModal from '../../components/upload-id-card-modal.vue'
  import { Message, Modal } from '@arco-design/web-vue'

  const visible = ref(false)
  const okLoading = ref(false)

  // 列表页，修改承租人信息时 isListEditMember 传为 true
  const props = defineProps({
    // 场景
    mode: {
      type: String,
      default: 'createOrder', // editLesseeMemberModal （编辑承租人弹窗）| createOrder（创建订单）| editOrder（编辑订单）
    },
    isListEditMember: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: '',
    },
  })

  const pageFormItemSize = computed(() => {
    return props.mode == 'editLesseeMemberModal' ? '1/2' : '1/3'
  })
  const pageFormRowGutter = computed(() => {
    return props.mode == 'editLesseeMemberModal' ? 56 : undefined
  })

  // 接收 form 和 dict
  const form = inject('form')
  const dict = inject('dict')
  const modalFormRef = ref()
  const modalForm = ref({
    memberName: '',
    memberPhone: '',
  })
  const modalRules = ref({
    memberPhone: [
      { required: true, message: '请输入联系电话' },
      { minLength: 11, match: /^[0-9]+$/, message: '仅支持数字，长度11位' },
    ],
    memberName: { required: true, message: '请输入承租人' },
  })

  const onInput = (value) => {
    form.value.emergencyContactPhone = value.replace(/\D/g, '')
  }

  // 用户信息
  const memberInfo = ref({})
  // 是否显示驾驶证上传按钮
  const showUploadDriverBtn = ref(false)
  // 是否显示身份证明上传按钮
  const showUploadIdCardBtn = ref(false)
  // 切换客户类型
  const changeMemberTypeFn = () => {
    updateFormMembder({}, form.value)
    showUploadDriverBtn.value = false
    showUploadIdCardBtn.value = false
  }
  // 切换企业
  const changeClientFn = () => {
    updateFormMembder({}, form.value)
  }
  // 切换企业承租人
  const changeClientMemberFn = (val, option) => {
    updateFormMembder(option, form.value)
  }

  const formRef = inject('formRef')
  const tmpPhone = ref('')

  // 承租人输入回调
  const memberPhoneList = ref([])
  const memberNameInputFn = useDebounceFn((form) => {
    const name = form.memberName
    if (name) {
      if (tmpPhone.value) return // 先输入联系电话时不请求

      form.memberPhone = undefined // 改变承租人姓名时清空手机号
      form.memberName = name
      getMemberInfo({ memberName: name }).then(({ result }) => {
        // 清空会员手机号值
        form.memberId = undefined
        // form.memberPhone = undefined

        if (result.length > 0) {
          memberPhoneList.value = result
          // 若承租人一个电话，则为输入框，并且默认带出，且不可修改
          if (result.length == 1) {
            const option = result[0]
            updateFormMembder(option, form)
            showUploadDriverBtn.value = !option.driverFrontFileId || !option.driverReverseFileId
            showUploadIdCardBtn.value = !option.idCardFrontFileId || !option.idCardReverseFileId
          }
        } else {
          updateFormMembder({}, form)
          form.cardType = 0 // 证件类型，默认身份证
          form.memberName = name
          form.memberPhone = tmpPhone.value || undefined
          // 清空企业id
          form.clientId = undefined
          showUploadDriverBtn.value = true
          showUploadIdCardBtn.value = true
          memberPhoneResult.value = false
          memberPhoneList.value = []
        }

        formRef.value.validateField('memberPhone')
      })
    } else {
      updateFormMembder({}, form)
      form.cardType = 0 // 证件类型，默认身份证
      form.memberName = name
      form.memberPhone = tmpPhone.value || undefined
      // 清空企业id
      form.clientId = undefined
      showUploadDriverBtn.value = false
      showUploadIdCardBtn.value = false
      memberPhoneResult.value = false
      memberPhoneList.value = []
    }
  }, 800)

  // 联系电话输入回调 13333333388
  const memberPhoneResult = ref(false)
  const memberPhoneInputFn = useDebounceFn((phone, ev, form) => {
    console.log('memberPhoneInputFn', phone)

    /**
     * 1. 输入或者修改(不完全删除)联系电话时
     *    1.1 若有对应承租人，则为默认带出承租人，且不可修改
     *    1.2 若没有对应承租人，承租人可以填写
     * 2. 删除(完全删除)或清空联系电话时，清空承租人姓名，再走 1 逻辑
     */

    if (phone && /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)) {
      form.memberName = undefined
      form.memberPhone = phone
      tmpPhone.value = phone

      findByPhone({ phone: phone }).then(({ result }) => {
        // 存在当前手机号对应的会员
        if (result) {
          updateFormMembder(result, form)
          memberPhoneResult.value = true
        } else {
          // 兼容情况
          // 输入了一个已有会员的手机号，自动填充承租人、证件号
          // 再次输入一个没有会员的手机号，清空证件号
          if (form.memberId) {
            updateFormMembder({ memberName: form.memberName }, form)
          }
          form.cardType = 0 // 证件类型，默认身份证
          form.memberPhone = phone
          tmpPhone.value = phone
          // 清空企业id
          form.clientId = undefined
          showUploadDriverBtn.value = true
          showUploadIdCardBtn.value = true
          memberPhoneResult.value = false
        }

        formRef.value.validateField('memberName')
      })
    } else {
      updateFormMembder({}, form)
      form.cardType = 0 // 证件类型，默认身份证
      form.memberPhone = phone
      tmpPhone.value = phone
      // 清空企业id
      form.clientId = undefined
      showUploadDriverBtn.value = false
      showUploadIdCardBtn.value = false
      memberPhoneResult.value = false
    }
  }, 800)

  const memberPhoneChange = (val, form) => {
    if (val) {
      const option = memberPhoneList.value.find((it) => it.phone == val)
      if (option) form.memberId = option.id

      findByPhone({ phone: val }).then(({ result }) => {
        // 存在当前手机号对应的会员
        updateFormMembder(result, form)
      })
    } else {
      updateFormMembder({}, form)
      form.cardType = 0 // 证件类型，默认身份证
      memberPhoneList.value = []
      tmpPhone.value = null
      showUploadDriverBtn.value = false
      showUploadIdCardBtn.value = false
    }
  }

  // 更新 form 客户相关信息
  const updateFormMembder = (option = {}, form) => {
    memberInfo.value = option
    form.memberId = option.id
    form.memberPhone = option.phone
    form.memberName = option.memberName
    form.cardType = option.cardType
    form.cardNumber = option.cardNumber
    form.cardAddress = option.cardAddress
    // 驾驶证正反面信息
    form.driverFrontFileId = option.driverFrontFileId
    form.driverReverseFileId = option.driverReverseFileId
    // 身份证明正反面信息
    form.idCardFrontFileId = option.idCardFrontFileId
    form.idCardReverseFileId = option.idCardReverseFileId

    // option 不为空
    if (option?.id) {
      showUploadDriverBtn.value = !form.driverFrontFileId || !form.driverReverseFileId
      showUploadIdCardBtn.value = !form.idCardFrontFileId || !form.idCardReverseFileId
    } else {
      if (form !== modalForm.value) {
        showUploadDriverBtn.value = false
        showUploadIdCardBtn.value = false
      }
    }
    // 紧急联系人和手机号
    form.emergencyContactName = option.emergencyContactName || ''
    form.emergencyContactPhone = option.emergencyContactPhone || ''
  }

  // 上传驾驶证点击
  const uploadDriverLicenseModalRef = ref()
  const uploadDriverLicenseFn = () => {
    uploadDriverLicenseModalRef.value.open(form.value.memberId, form.value.driverFrontFileId, form.value.driverReverseFileId)
  }

  // 上传驾驶证完成
  const uploadSuccessFn = (result) => {
    const { driverFrontFileId, driverReverseFileId } = result
    // 更新驾驶证正反面 id
    form.value.driverFrontFileId = driverFrontFileId
    form.value.driverReverseFileId = driverReverseFileId
  }

  // 更新是否显示上传驾驶证按钮
  const updateUploadDriverBtnStatus = (show) => {
    showUploadDriverBtn.value = show
  }
  // 更新 memberInfo
  const updateMemberInfo = (info = {}) => {
    memberInfo.value = info
  }

  // 上传身份证明点击
  const uploadIdCardModalRef = ref()
  const uploadIdCardFn = () => {
    uploadIdCardModalRef.value.open(form.value.memberId, form.value.cardType, form.value.idCardFrontFileId, form.value.idCardReverseFileId)
  }

  // 上传身份证明完成
  const uploadIdCardSuccessFn = (result) => {
    const { idCardFrontFileId, idCardReverseFileId } = result
    // 更新身份证明正反面 id
    form.value.idCardFrontFileId = idCardFrontFileId
    form.value.idCardReverseFileId = idCardReverseFileId
  }

  // 更新是否显示上传身份证明按钮
  const updateUploadIdCardBtnStatus = (show) => {
    showUploadIdCardBtn.value = show
  }

  const onChangeMemberInfo = () => {
    if (form.value.memberName && form.value.memberPhone) {
      checkMemberPhone({ name: form.value.memberName, phone: form.value.memberPhone, type: 1 }).then(({ result }) => {
        console.log('result', result)
        if (!result.msg) {
          modalForm.value.memberName = form.value.memberName
          modalForm.value.memberPhone = form.value.memberPhone
          modalForm.value.id = form.value.memberId
          visible.value = true
        } else {
          Message.error(result.msg)
        }
      })
    } else {
      Message.error('请先输入承租人和联系电话')
    }
  }

  const onCancel = () => {
    visible.value = false
  }

  const onConfirm = () => {
    modalFormRef.value.validate((error) => {
      okLoading.value = true
      if (!error) {
        checkMemberPhone({ id: modalForm.value.id, name: modalForm.value.memberName, phone: modalForm.value.memberPhone, type: 2 })
          .then(() => {
            Modal.confirm({
              ...{
                title: '提示',
                simple: true,
                cancelText: '关闭',
                okText: '确认',
                content: '确认修改承租人信息吗？',
              },
              onOk: () => {
                visible.value = false
                okLoading.value = false
                form.value.memberName = modalForm.value.memberName
                form.value.memberPhone = modalForm.value.memberPhone
              },
            })
          })
          .finally(() => {
            okLoading.value = false
          })
      } else {
        okLoading.value = false
      }
    })
  }

  const againConfirmVisible = ref(false)
  const onAgainCancel = () => {
    againConfirmVisible.value = false
  }
  const onAgainConfirm = () => {
    againConfirmVisible.value = false
    visible.value = false
    form.value.memberName = modalForm.value.memberName
    form.value.memberPhone = modalForm.value.memberPhone
  }

  defineExpose({
    updateUploadDriverBtnStatus,
    updateUploadIdCardBtnStatus,
    updateMemberInfo,
  })
</script>
<style lang="less" scoped>
  // 身份证明和驾驶证按钮排列
  .card-btns {
    display: flex;
    margin-top: 26px;
    .id-btn {
      margin-right: 10px;
    }
  }
  .edit-width {
    margin-left: -150px;
  }
</style>
